import "./PageAMap.less";
import "./icon/css/icon.less";
import { Component } from "refast";
import React from "react";
import { withRouter, Link } from "react-router";
import { Map, Marker, InfoWindow } from "react-amap";
import Heatmap from "react-amap-plugin-heatmap";
import MarkerClusterer from "./../../components/amap-custom-layers/clusterer/MarkerClusterer";
import Category from "../../components/amap-custom-layers/category/Category";
import MyMenu from "../../components/amap-custom-layers/menu/MyMenu";
import Message from "../../components/amap-custom-layers/message/Message";
import FgfcEchartsMap from "../../components/fgfcmap";
import logic from "./logic";
import Home from "./../../pages/home/PageHome";
import Tag from "uxcore-tag";
import Layout, { Left, Right } from "uxcore-layout";
import Head from "../../components/head";
import Button from "uxcore-button";
import Dialog from "uxcore-dialog";
import Animate from "react-simple-animate";
import Form from "uxcore-form";
import classnames from "classnames";
import Icon from "uxcore-icon";
import { zhgdDpUrl } from "./../../app/variables";
const { FormRow, InputFormField } = Form;
const { RightAddon } = InputFormField;
import emitter from "./../ev";
import Alert from "uxcore-alert";

class PageAMap extends Component {
  constructor(props) {
    super(props, logic);

    let t = this;
    t.markerEvents = {
      click: (e, marker) => {
        t.onMarkerClicked(marker.getExtData());
      },
    };
    t.infoWindowEvents = {
      close: () => {
        t.closeInfoWindow();
      },
    };
    t.onWindowResize = t.onWindowResize.bind(t);
    t.onMessageClick = t.onMessageClick.bind(t);
    t.onXxlsShowOrHide = t.onXxlsShowOrHide.bind(t);
    t.updateYcsj = t.updateYcsj.bind(t);
    t.onMenuClick = t.onMenuClick.bind(t);
    t.onCategoryClick = t.onCategoryClick.bind(t);
    t.handleGcTitleClick = t.handleGcTitleClick.bind(t);
    t.onMapDragend = t.onMapDragend.bind(t);
    t.onMapZoomChange = t.onMapZoomChange.bind(t);
    t.receiveJdMessage = t.receiveJdMessage.bind(t);
    t.handleYcAlertMessage = t.handleYcAlertMessage.bind(t);
    t.onMarkerClicked = t.onMarkerClicked.bind(t);
    t.login = t.login.bind(t);
    t.handleShowPassChange = t.handleShowPassChange.bind(t);
    t.onCameraTagClick = t.onCameraTagClick.bind(t);
    t.showCameraDialog = t.showCameraDialog.bind(t);
    t.handleCantonCountMapChange = t.handleCantonCountMapChange.bind(t);
    t.handleLjdgCountClick = t.handleLjdgCountClick.bind(t);
    t.changeDispatchSumDialogVisible = t.changeDispatchSumDialogVisible.bind(t);
  }

  login() {
    this.dispatch("login", {
      user: this.refs.form.getValues(true).values,
      key: this.menuKey(this.props.location.pathname),
    });
  }

  handleShowPassChange() {
    let me = this;
    me.setState({
      showPass: !me.state.showPass,
    });
  }

  onWindowResize() {
    this.setState({
      wHeight: window.innerHeight - 140,
      messageContentHeight: window.innerHeight - 777,
    });
  }

  menuKey(pathname) {
    let menuKey = "default";
    if (pathname.indexOf("/xmmx") === 0) {
      menuKey = "xmmx";
    } else if (pathname.indexOf("/xmzx") === 0) {
      menuKey = "xmzx";
    } else if (pathname.indexOf("/xytx") === 0) {
      menuKey = "xmmx";
    } else if (pathname.indexOf("/grxx") === 0) {
      menuKey = "xmmx";
    } else if (pathname.indexOf("/ycjk") === 0) {
      menuKey = "ycjk";
    } else if (pathname.indexOf("/ycgd") === 0) {
      menuKey = "ycjk";
    } else if (pathname.indexOf("/fgfc") === 0) {
      menuKey = "fgfc";
    } else {
      menuKey = "default";
    }
    return menuKey;
  }

  componentWillMount() {
    for (let i = localStorage.length - 1; i >= 0; i--) {
      if (localStorage.key(i).indexOf("_AMap_") !== -1) {
        localStorage.removeItem(localStorage.key(i));
      }
    }

    this.dispatch(["init"], {
      key: this.menuKey(this.props.location.pathname),
    });
  }

  componentDidMount() {
    window.addEventListener("resize", this.onWindowResize);

    this.eventEmitter = emitter.addListener("FGMapShow", (value) => {
      let { fgMapShow } = this.state;
      this.setState({
        fgMapShow: !fgMapShow,
      });
    });
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.onWindowResize);

    emitter.removeListener(this.eventEmitter);
  }

  shouldComponentUpdate(nextProps, nextState) {
    const thisProps = this.props || {},
      thisState = this.state || {};
    if (
      Object.keys(thisProps).length !== Object.keys(nextProps).length ||
      Object.keys(thisState).length !== Object.keys(nextState).length
    ) {
      return true;
    }

    for (const key in nextProps) {
      if (thisProps[key] !== nextProps[key]) {
        return true;
      }
    }

    for (const key in nextState) {
      if (thisState[key] !== nextState[key]) {
        return true;
      }
    }
    return true;
  }

  onMarkerClicked(props) {
    if (props.markerType === "ENG") {
      this.context.router.push("/xmmx/" + props.markerId);
    } else if (props.markerType === "YC") {
      // this.context.router.push('/ycgd/' + props.markerId);
    }
    this.dispatch("onMarkerClicked", props);
  }

  closeInfoWindow() {
    this.dispatch("setInfoWindowVisible", { visible: false });
  }

  onMessageClick(message) {
    if (message.type === "JD") {
      this.dispatch(["onMessageClick"], { message: message });
    } else if (message.type === "YA" || message.type === "RA") {
      this.dispatch(
        [
          "changeMenu2",
          "changeCurrentMarkers2",
          "initCategory2",
          "initHeatMapData2",
          "setHeatMapVisible2",
          "setXxlsVisible2",
          "onMessageClick",
        ],
        { key: "ycjk", xxlsVisible: false, message: message }
      );
      this.context.router.push("/ycjk");
    }
  }

  onXxlsShowOrHide(visible) {
    this.dispatch("setXxlsVisible2", { xxlsVisible: visible });
  }

  updateYcsj(data) {
    this.dispatch(["updateYcsj", "updateInfoWindowContent"], { ycData: data });
  }

  receiveJdMessage(message) {
    this.dispatch(["receiveJdMessage"], message);
  }

  handleYcAlertMessage(message) {
    this.dispatch(["handleYcAlertMessage", "showYcAlertMessage"], message);
  }

  onMenuClick(menuKey) {
    if (menuKey === "jzy") {
      return;
    }
    let route = "default";
    let key = "default";
    switch(menuKey) {
      case "default":
        route = "/default";
        key = "default";
        break;
      case "xmzx":
        route = "/xmzx";
        key = "xmzx";
        break;
      case "xmmx":
        if (
          this.state.engMarkers &&
          this.state.engMarkers.length > 0 &&
          "customOpts" in this.state.engMarkers[0]
        ) {
          route = "/xmmx/" + this.state.engMarkers[0].customOpts.id;
        } else {
          route = "/xmmx/xxxxxx";
        }
        key = "xmmx";
        break;
      case "ycjk":
        route = "/ycjk";
        key = "ycjk";
        break;
      case "fgfc":
        route = "/fgfc";
        key = "fgfc";
        break;
      default:
        route = "/default";
        key = "default";
        break;
    }
    this.dispatch(
      [
        "changeMenu2",
        "changeCurrentMarkers2",
        "initCategory2",
        "initHeatMapData2",
        "setHeatMapVisible2",
        "setXxlsVisible2",
      ],
      { key, xxlsVisible: false }
    );
    this.context.router.push(route);
  }

  onMapDragend(props) {
    this.dispatch("onMapDragend", props);
  }

  onMapZoomChange(props) {
    this.dispatch("onMapZoomChange", props);
  }

  onCategoryClick(props) {
    this.dispatch("onCategoryClick", props);
  }

  handleGcTitleClick(id) {
    this.dispatch(
      [
        "changeMenu2",
        "changeCurrentMarkers2",
        "initCategory2",
        "onGcTitleClick2",
        "setHeatMapVisible2",
      ],
      {
        id: id,
        key: "xmmx",
      }
    );
  }

  onCameraTagClick(camera) {
    this.dispatch("showCameraDialog", {
      visible: true,
      selectedCamera: { cameraName: camera.name, unitId: camera.cameraUuid },
    });
  }

  showCameraDialog(visible) {
    this.dispatch("showCameraDialog", { visible: visible });
  }

  handleCantonCountMapChange(props) {
    this.dispatch("cantonCountMapChange", props);
  }

  // 复工复产页面累计已到岗人数点击处理
  handleLjdgCountClick() {
    // 跳转到default页面并弹出派工页面
    this.dispatch(
      [
        "changeMenu2",
        "changeCurrentMarkers2",
        "initCategory2",
        "setHeatMapVisible2",
      ],
      {
        key: "default",
      }
    );
    this.context.router.push('/default');
    this.changeDispatchSumDialogVisible(true);
  }

  changeDispatchSumDialogVisible(visible) {
    this.setState({
      dispatchSumDialogVisible: visible,
    });
  }

  renderInfoWindowContent(params) {
    if (params && params.id) {
      switch (params.type) {
        case "MSG":
          return (
            <div id={params.id}>
              <h3>{params.title}</h3>
              <br />
              <h4>消息内容：{params.content}</h4>
            </div>
          );
          break;
        case "ENG":
          const type = params.junGong ? 'info' : 'success';
          return (
            <div id={params.id}>
              <a href={`#/xmmx/${params.id}`}>
                <h3>{params.title}</h3>
              </a>
              <Tag addTags={false}>
                <Tag.Item type={type}>{params.junGong ? '竣工' : '在建'}</Tag.Item>
              </Tag>
              <br />
              <h4>地址：{params.content}</h4>
              <br />
              <h4>
                进入
                <a href={`${zhgdDpUrl}${params.zhgdId}`} target="_blank">
                  智慧工地
                </a>
              </h4>
            </div>
          );
          break;
        case "YC":
          let eData = params.eData;
          let sprinklestatus;
          switch (params.sprinklestatus) {
            case "1":
              sprinklestatus = "关闭";
              break;
            case "2":
              sprinklestatus = "开启";
              break;
            case "3":
              sprinklestatus = "异常";
              break;
            default:
              sprinklestatus = "-";
              break;
          }
          let fogcannonstatus;
          switch (params.fogcannonstatus) {
            case "1":
              fogcannonstatus = "关闭";
              break;
            case "2":
              fogcannonstatus = "开启";
              break;
            case "3":
              fogcannonstatus = "异常";
              break;
            default:
              fogcannonstatus = "-";
              break;
          }
          const camera = params.camera;
          return (
            <div id={params.id} className="infowindow-div">
              <h3>{params.title}</h3>
              <br />
              {/*
              <div className="info-window-camera">
                <h4>工地视频监控</h4>
                <div>
                  {camera && camera.length > 0 ? (
                    <Tag addTags={false}>
                      {camera.map((c) => (
                        <Tag.Item
                          key={c.cameraUuid}
                          onClick={() => this.onCameraTagClick(c)}
                        >
                          {c.name}
                        </Tag.Item>
                      ))}
                    </Tag>
                  ) : (
                    <div>暂无数据</div>
                  )}
                </div>
              </div>
              */}
              <div>
                <h4>{`扬尘监控数据（更新时间：${
                  eData ? (eData.saveTime ? eData.saveTime : "-") : "-"
                }）`}</h4>
                <div className="info-window-table">
                  <div className="info-window-table-tr">
                    <div className="info-window-table-th">PM2.5(μg/m³)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.pmTwo : "-"}
                    </div>
                    <div className="info-window-table-th">PM10(μg/m³)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.pmTen : "-"}
                    </div>
                  </div>
                  <div className="info-window-table-tr">
                    <div className="info-window-table-th">噪音(dB)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.tsp : "-"}
                    </div>
                    <div className="info-window-table-th">温度(℃)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.temperature : "-"}
                    </div>
                  </div>
                  <div className="info-window-table-tr">
                    <div className="info-window-table-th">湿度(%)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.humidity : "-"}
                    </div>
                    <div className="info-window-table-th">风速(M/S)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.windSpeed : "-"}
                    </div>
                  </div>
                  <div className="info-window-table-tr">
                    <div className="info-window-table-th">风向</div>
                    <div className="info-window-table-td">
                      {eData ? eData.windDeriction : "-"}
                    </div>
                    <div className="info-window-table-th">气压(Pa)</div>
                    <div className="info-window-table-td">
                      {eData ? eData.atmosphere : "-"}
                    </div>
                  </div>
                  <div className="info-window-table-tr">
                    <div className="info-window-table-th">喷淋状态</div>
                    <div className="info-window-table-td">{sprinklestatus}</div>
                    <div className="info-window-table-th">雾炮状态</div>
                    <div className="info-window-table-td">
                      {fogcannonstatus}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
          break;
        default:
          return <div />;
          break;
      }
    } else {
      return <div />;
    }
  }

  mapRender() {
    if (this.state.fgMapShow) {
      return (
        <div className="map">
          <Message
            style={{ marginRight: "600px" }}
            token={this.state.token}
            location={this.props.location}
            xxlsOpts={this.state.xxlsOpts}
            height={this.state.messageContentHeight}
            content={this.state.messageContent}
            onMessageClick={this.onMessageClick}
            onXxlsShowOrHide={this.onXxlsShowOrHide}
            onUpdateYcsj={this.updateYcsj}
            receiveJdMessage={this.receiveJdMessage}
            handleYcAlertMessage={this.handleYcAlertMessage}
          />
          <iframe
            style={{ width: "100%", height: "100%", overflow: "visible" }}
            src={"http://36.148.23.13:2228/cyry/#/index/fgmap"}
            width="100%"
            scrolling="no"
            frameBorder="0"
          />
          <MyMenu
            location={this.props.location}
            curKey={this.state.menuKey}
            onMenuClick={this.onMenuClick}
            currentMarker={this.state.amapOptions.currentMarker}
            userconfig={this.state.userconfig}
          />
        </div>
      );
    }

    // 复工复产echarts地图
    if (this.state.menuKey === "fgfc") {
      return (
        <div className="map">
          <FgfcEchartsMap
            data={this.state.fgfc}
            onCantonCountMapChange={this.handleCantonCountMapChange}
          />
          <Message
            style={{ marginRight: "600px" }}
            token={this.state.token}
            location={this.props.location}
            xxlsOpts={this.state.xxlsOpts}
            height={this.state.messageContentHeight}
            content={this.state.messageContent}
            onMessageClick={this.onMessageClick}
            onXxlsShowOrHide={this.onXxlsShowOrHide}
            onUpdateYcsj={this.updateYcsj}
            receiveJdMessage={this.receiveJdMessage}
            handleYcAlertMessage={this.handleYcAlertMessage}
          />
          <MyMenu
            location={this.props.location}
            curKey={this.state.menuKey}
            onMenuClick={this.onMenuClick}
            currentMarker={this.state.amapOptions.currentMarker}
            userconfig={this.state.userconfig}
          />
        </div>
      );
    }

    const { heatmapProps } = this.state.amapOptions;
    // 热力图
    let heatMap =
      heatmapProps.dataSet.data && heatmapProps.dataSet.data.length > 0 ? (
        <Heatmap {...heatmapProps} />
      ) : null;

    let infoWindowContentDiv = this.renderInfoWindowContent(
      this.state.amapOptions.infoWindowContent
    );

    return (
      <Map
        center={this.state.amapOptions.center}
        plugins={this.state.amapOptions.amapPlugins}
        events={this.state.amapOptions.amapEvents}
      >
        {heatMap}
        <MarkerClusterer
          markers={this.state.amapOptions.currentMarkers}
          markerClick={this.onMarkerClicked}
          {...this.state.amapOptions.markerClusterer.opts}
        />
        <Category
          onClick={this.onCategoryClick}
          currentMarkerCategory={this.state.amapOptions.currentMarkerCategory}
        />
        <MyMenu
          isBDMap
          location={this.props.location}
          curKey={this.state.menuKey}
          onMenuClick={this.onMenuClick}
          currentMarker={this.state.amapOptions.currentMarker}
          userconfig={this.state.userconfig}
        />
        <Message
          token={this.state.token}
          location={this.props.location}
          xxlsOpts={this.state.xxlsOpts}
          height={this.state.messageContentHeight}
          content={this.state.messageContent}
          onMessageClick={this.onMessageClick}
          onXxlsShowOrHide={this.onXxlsShowOrHide}
          onUpdateYcsj={this.updateYcsj}
          receiveJdMessage={this.receiveJdMessage}
          handleYcAlertMessage={this.handleYcAlertMessage}
        />

        {this.state.amapOptions.currentMsgMarker.opts && (
          <Marker
            events={this.markerEvents}
            {...this.state.amapOptions.currentMsgMarker.opts}
          />
        )}

        <InfoWindow
          events={this.infoWindowEvents}
          {...this.state.amapOptions.infoWindow}
        >
          {infoWindowContentDiv}
        </InfoWindow>
      </Map>
    );
  }

  render() {
    let infoWindowContentDiv = this.renderInfoWindowContent(
      this.state.amapOptions.infoWindowContent
    );

    const { heatmapProps } = this.state.amapOptions;
    // 热力图
    let heatMap =
      heatmapProps.dataSet.data && heatmapProps.dataSet.data.length > 0 ? (
        <Heatmap {...heatmapProps} />
      ) : null;

    let UIModel = {};
    let menu_key = this.props.location.pathname.split("/")[1];
    if (
      this.state.userconfig &&
      "menuData" in this.state.userconfig &&
      this.state.userconfig.menuData &&
      this.state.userconfig.menuData.length > 0
    ) {
      let menu = this.state.userconfig.menuData[0].children.find((menu) => {
        return menu.data.url === menu_key;
      });
      if (menu && "children" in menu && menu.children) {
        UIModel = menu.children;
      }
    }

    return (
      <div>
        <Dialog
          title="请先登录系统"
          width="500"
          footer=""
          visible={!this.state.isLogin}
          wrapClassName="vertical-center-dailog"
        >
          <Form ref="form" instantValidate={true}>
            <FormRow>
              <InputFormField
                jsxflex="2"
                jsxname="username"
                jsxlabel="请输入用户名"
                inputType="text"
              >
                <RightAddon>
                  <Icon name="ren" />
                </RightAddon>
              </InputFormField>
            </FormRow>
            <FormRow>
              <InputFormField
                jsxflex="2"
                jsxname="password"
                jsxlabel="请输入密码"
                inputType={this.state.showPass ? "text" : "password"}
              >
                <RightAddon>
                  <i
                    className={classnames({
                      "kuma-icon": true,
                      "kuma-icon-privacy": !this.state.showPass,
                      "kuma-icon-public": this.state.showPass,
                    })}
                    onClick={this.handleShowPassChange}
                  />
                </RightAddon>
              </InputFormField>
            </FormRow>
          </Form>

          {this.state.errorMsg !== "" && (
            <Alert
              message={this.state.errorMsg}
              type="error"
              hasContainer={true}
            />
          )}

          <div className="center">
            <Button
              onClick={this.login}
              style={{ marginRight: "12px" }}
              id="loginBtn"
            >
              确定登录
            </Button>
          </div>
        </Dialog>

        <Animate {...this.state.ant}>
          {this.state.isLogin && (
            <div>
              <Head
                handleGcTitleClick={this.handleGcTitleClick}
                title={this.state.systemName}
              />
              <Layout className="main">
                <Left width="980">
                  <Home
                    dispatchSumDialogVisible={this.state.dispatchSumDialogVisible}
                    changeDispatchSumDialogVisible={this.changeDispatchSumDialogVisible}
                    userconfig={this.state.userconfig}
                    token={this.state.token}
                    UIModel={UIModel}
                    children={this.props.children}
                    location={this.props.location}
                    onGcTitleClick={this.handleGcTitleClick}
                    onFgfcMapTabsChange={this.handleCantonCountMapChange}
                    onLjdgCountClick={this.handleLjdgCountClick}
                  />
                </Left>
                <Right adaptive={true}>
                  <div style={{ height: this.state.wHeight }}>
                    {this.mapRender()}
                  </div>
                </Right>
              </Layout>
            </div>
          )}
        </Animate>

        <Dialog
          title={this.state.cameraDialog.title}
          width={660}
          onCancel={() => this.showCameraDialog(false)}
          onOk={() => this.showCameraDialog(false)}
          visible={this.state.cameraDialog.visible}
          transitionName="slideDown"
        >
          {this.state.cameraDialog.content}
        </Dialog>
      </div>
    );
  }
}

PageAMap.contextTypes = {
  router: React.PropTypes.isRequired,
};

export default withRouter(PageAMap);
